package com.polaris.live.utils

import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.polaris.live.App
import com.polaris.live.utils.file.FileUtils
import java.io.File

/**
 * 音频播放器
 *
 * @author Created by 半仙 on 2024/9/6/006 20:42
 */
class AudioPlayProxy {
    //播放器
    private var mediaPlayer: MediaPlayer? = null

    //音频地址
    private var playUri: Uri? = null

    //保存音量
    private var savedVolume = -1

    //是否需要循环
    private var needLoop = false

    //生命周期管理
    private var mLifecycleOwner: LifecycleOwner? = null

    /**
     * 初始化
     * @param soundResId 音频id
     * @param needLoop 默认不循环
     * @param lifecycle 生命周期 如果不传递就自己管理
     */
    fun init(url: String, needLoop: Boolean = false, lifecycle: LifecycleOwner? = null) {
        this.needLoop = needLoop
        mLifecycleOwner = lifecycle
        val path = FileUtils.getFilePath(FileUtils.getAudioFile(), url)
        playUri = Uri.fromFile(File(path))

        mLifecycleOwner?.lifecycle?.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    recycle()
                }
            }
        })
    }

    fun playSound(needMaxVolume: Boolean = false) {
        if (mLifecycleOwner?.lifecycle?.currentState == Lifecycle.State.DESTROYED) {
            return
        }

        val showUri = playUri ?: return
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer().apply {
                isLooping = needLoop
                setDataSource(App.instance, showUri)
                prepareAsync()
                setOnPreparedListener {
                    it.start()
                }
                setOnErrorListener { _, what, _ ->
                    return@setOnErrorListener false
                }
            }
        }
        if (needMaxVolume) {
            (App.instance.getSystemService(Context.AUDIO_SERVICE) as AudioManager)
                .apply {
                    savedVolume = getStreamVolume(AudioManager.STREAM_MUSIC)
                    setStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        getStreamMaxVolume(AudioManager.STREAM_MUSIC),
                        0
                    )
                }
        }
        mediaPlayer?.start()
    }

    fun stopPlay() {
        if (savedVolume != -1) {
            (App.instance.getSystemService(Context.AUDIO_SERVICE) as AudioManager)
                .apply {
                    setStreamVolume(AudioManager.STREAM_MUSIC, savedVolume, 0)
                    savedVolume = -1
                }
        }
        mediaPlayer?.release()
        mediaPlayer = null
    }

    fun recycle() {
        stopPlay()
        playUri = null
        mLifecycleOwner = null
    }

    companion object {
        fun instance(): AudioPlayProxy {
            return Proxy.instance
        }

        private object Proxy {
            var instance = AudioPlayProxy()
        }
    }
}